package com.example.jnnews;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class RegisterActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private SharedPreferences sharedPreferences;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        Button btnRegister = findViewById(R.id.btn_register);
        sharedPreferences = getSharedPreferences("jnnews_prefs", MODE_PRIVATE);

        btnRegister.setOnClickListener(v -> {
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            if (validateInput(username, password)) {
                registerUser(username, password);
            }
        });
    }

    private boolean validateInput(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void registerUser(String username, String password) {
        List<User> users = getUsers();
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        users.add(new User(username, password));
        saveUsers(users);

        Intent resultIntent = new Intent();
        resultIntent.putExtra("username", username);
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    private List<User> getUsers() {
        String json = sharedPreferences.getString("users", "");
        if (json.isEmpty()) return new ArrayList<>();
        Type type = new TypeToken<ArrayList<User>>(){}.getType();
        return gson.fromJson(json, type);
    }

    private void saveUsers(List<User> users) {
        String json = gson.toJson(users);
        sharedPreferences.edit()
                .putString("users", json)
                .apply();
    }
}